package com.mqb.util;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import java.nio.charset.StandardCharsets;

public class ByteBufUtil {

    /**
     * 将发送的信息转为 ByteBuf，并在头部加上4个字节表示长度
     * @param msg msg
     * @return ByteBuf
     */
    public static ByteBuf transferWithHead(String msg){
        byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
        ByteBuf byteBuf = ByteBufAllocator.DEFAULT.heapBuffer(bytes.length + 4);
        System.out.println(byteBuf);
        byteBuf.writeInt(bytes.length);
        byteBuf.writeBytes(bytes);
        return byteBuf;
    }

    public static ByteBuf transferWithHead(Object obj){
        return transferWithHead(JSONObject.toJSONString(obj));
    }
}
